#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //信号和槽连接
    connect(&tcpSocket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(&tcpSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    connect(&tcpSocket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(&tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
            this,SLOT(onError()));
}

Dialog::~Dialog()
{
    delete ui;
}

//和服务器连接成功时执行的槽函数
void Dialog::onConnected()
{
    ui->status->setText("在线");
    ui->connect->setEnabled(false);
    //向服务器发送进入聊天室提示消息
    QString msg = "7+乘客"+ username + "已连接";
    //toUtf8:QString转换QByteArray
    tcpSocket.write(msg.toUtf8());

}
//和服务器断开连接时执行的槽函数
void Dialog::onDisconnected()
{
    ui->status->setText("离线");
    ui->connect->setEnabled(true);
}
//网络异常执行的槽函数
void Dialog::onError()
{
    //errorString():获取网络异常的原因
    QMessageBox::critical(this,"ERROR",tcpSocket.errorString());
}
//接收消息的槽函数
void Dialog::onReadyRead()
{
    if(tcpSocket.bytesAvailable()){
        //接收消息
        QString buff = tcpSocket.readAll();
        QStringList buf = buff.split('+');
        if(buf[0]=="2y"){
            QMessageBox::about(NULL, "乘客端", "打车成功！");
        }else if(buf[0]=="2n"){
            QMessageBox::about(NULL, "乘客端", "打车失败！");
        }else if(buf[0]=="3y"){
            QMessageBox::about(NULL, "乘客端", "预约成功！");
        }else if(buf[0]=="3n"){
            QMessageBox::about(NULL, "乘客端", "预约失败！");
        }else if(buf[0]=="7"){
            QMessageBox::about(NULL, "乘客端", buf[1]);
        }
    }
}
//处理连接按钮的槽函数
void Dialog::on_connect_clicked()
{
    ui->status->setText("离线");
    ui->connect->setEnabled(true);
    tcpSocket.connectToHost("127.0.0.1",8080);
}
//处理打车按钮的槽函数
void Dialog::on_take_clicked()
{
    QString msg = "2+"+ui->bloc->text()+"+"+ui->eloc->text();
    tcpSocket.write(msg.toUtf8());
}
//处理预约打车按钮的槽函数
void Dialog::on_order_clicked()
{
    QString msg = "3+"+ui->time->text()+"+"+ui->bloc->text()+"+"+ui->eloc->text();
    tcpSocket.write(msg.toUtf8());
}
//窗口显示的槽函数
void Dialog::sshow(QString s)
{
    this->show();
    ui->username->setText(s);
    username=ui->username->text();
    //连接服务器
    tcpSocket.connectToHost("127.0.0.1",8080);
}
